import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import accuracy_score
from sklearn.tree import DecisionTreeClassifier
import matplotlib.pyplot as plt

# 读取数据
data = pd.read_csv('cleaned_Spambase.csv')

# 划分特征和标签
X = data.iloc[:, :-1]  # 获取除最后一列之外的所有列作为特征X
y = data.iloc[:, -1]   # 获取最后一列作为标签y

# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# 数据标准化
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)

# 构建决策树模型
dt_model = DecisionTreeClassifier(random_state=42)

# 训练决策树模型
dt_model.fit(X_train, y_train)

# 使用决策树模型进行分类
y_pred_dt = dt_model.predict(X_test)

# 计算准确率
accuracy_dt = accuracy_score(y_test, y_pred_dt)
print("Accuracy (Decision Tree): ", accuracy_dt)

# 绘制决策树的分类结果散点图
plt.scatter(X_test[:, 0], X_test[:, 1], c=y_pred_dt, cmap=plt.cm.Paired)
plt.xlabel('Feature 1')
plt.ylabel('Feature 2')
plt.title('Decision Tree Prediction')

plt.show()

